package com.gjy.rabbitmq.resolve;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 提供RabbitMQ队列和消息的监控功能
 *
 * @author gjy
 * @version 1.0
 * @since 2025-10-13 14:47:32
 */
public class MonitoringService {

    private static final Logger logger = LoggerFactory.getLogger(MonitoringService.class);

    /**
     * RabbitMQ通道
     */
    private final Channel channel;

    /**
     * 调度执行器
     */
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

    /**
     * 构造监控服务
     *
     * @param channel RabbitMQ通道
     */
    public MonitoringService(Channel channel) {
        this.channel = channel;
        logger.info("监控服务初始化完成");
    }

    /**
     * 启动监控
     */
    public void startMonitoring() {
        logger.info("启动RabbitMQ监控服务");

        // 定期检查未确认消息（每30秒）
        scheduler.scheduleAtFixedRate(this::checkUnconfirmedMessages, 0, 30, TimeUnit.SECONDS);

        // 定期检查队列积压（每60秒）
        scheduler.scheduleAtFixedRate(this::checkQueueBacklog, 0, 60, TimeUnit.SECONDS);

        logger.info("RabbitMQ监控服务启动完成");
    }

    /**
     * 检查未确认消息
     */
    private void checkUnconfirmedMessages() {
        logger.debug("执行未确认消息检查");
        // 实现未确认消息监控逻辑
        // 可以检查确认超时、重试次数等
    }

    /**
     * 检查队列积压
     */
    private void checkQueueBacklog() {
        logger.debug("执行队列积压检查");
        try {
            // 被动声明队列，获取队列信息而不创建队列
            AMQP.Queue.DeclareOk queueInfo = channel.queueDeclarePassive("reliable.queue");
            long messageCount = queueInfo.getMessageCount();

            logger.debug("队列消息数量: queue=reliable.queue, count={}", messageCount);

            // 如果队列积压消息过多，发出告警
            if (messageCount > 1000) {
                logger.warn("警告: 队列积压消息过多: queue=reliable.queue, count={}", messageCount);
                // 可以在这里发送告警通知，如邮件、短信等
            }
        } catch (IOException e) {
            logger.error("检查队列状态失败", e);
        }
    }

    /**
     * 停止监控
     */
    public void stopMonitoring() {
        logger.info("停止RabbitMQ监控服务");
        scheduler.shutdown();
        try {
            if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
        } catch (InterruptedException e) {
            scheduler.shutdownNow();
            Thread.currentThread().interrupt();
        }
        logger.info("RabbitMQ监控服务已停止");
    }

}
